package com.cangshi.controller;

import com.alibaba.fastjson.JSONObject;
import com.cangshi.exception.JsonException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Eoly on 2017/4/7.
 */
@ControllerAdvice
@ResponseBody
public class ExceptionAdvice {

    /**
     * 500 - Internal Server Error
     */

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(JsonException.class)
    public String handleRuntimeException(JsonException e) {
        JSONObject jsonObject = new JSONObject();
        // logger.error("服务运行异常", e);
        jsonObject.put("error", e.getError());
        jsonObject.put("msg", e.getMessage());
        return jsonObject.toString();
    }


    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(UnauthorizedException.class)
    public String handleUnauthorizedException(UnauthorizedException e, HttpServletResponse response) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("error", 500);
        jsonObject.put("msg", "You aren't had enough permission!");
        return jsonObject.toString();
    }
}
